//
//  HeartRateChartViewProvider.swift
//  DaRings
//
//  Created by 尹琼 on 2023/2/21.
//

import UIKit
import SwiftDate

/// 多色 心率 HRV 图表数据组合
open class HeartRateChartViewProvider: NSObject {
    
    
   public static func heartChartBarData(date: Date) ->(barData: [HeartBarData]?, max: Int, min: Int, avg: Int) {
        
        guard let heartRateModel = HeartRateModel.day(date: date) else {
            
            return (nil, 0, 0, 0)
        }
        
        let minute = 30
        let details = HeartRateDetailModel.detailModels(sqlLiteDatas: heartRateModel.hearts, date: heartRateModel.date, minute: minute)
        
        return chartDatas(detais: details, date: date, minute: minute)
        
    }
    
   public static func HRVChartBarData(date: Date) ->(barData: [HeartBarData]?, max: Int, min: Int, avg: Int) {
        
        guard let hrvModel = HRVModel.day(date: date) else {
            
            return (nil, 0, 0, 0)
        }
        
        let minute = 30
        let details = HeartRateDetailModel.detailModels(sqlLiteDatas: hrvModel.hrvs, date: hrvModel.date, minute: minute)
        
        return chartDatas(detais: details, date: date, minute: minute)
        
    }
    
    /// 获取最多 3个色的图表
    /// - Parameters:
    ///   - sqlLiteDatas: 数据库得到的数据数组
    ///   - date: 查询数据的日期
    ///   - minute: 数据数组中间间隔（比如 24小时心率 HRV 间隔 是30分钟 一个值）
    /// - Returns: [HeartBarData]
   public static func chartDatas(detais: [HeartRateDetailModel], date: Date, minute: Int) ->(barData: [HeartBarData]?, max: Int, min: Int, avg: Int) {
        
        
        guard let heartRateModel = HeartRateModel.day(date: date) else {
            
            return (nil, 0, 0, 0)
        }
        
        
        let details = heartRateModel.heartRateDetailModels()
        
        var max: Int = 0
        var min: Int = 255
        var avgAll: Int = 0
        var count: Int = 0
        
        var rangeAvg: Int = 0
        var rangeCount: Int = 0
        
        var maxDayTime: Int = 0
        var minDayTime: Int = 255
        
        var maxSleep: Int = 0
        var minSleep: Int = 255
        
        var maxTraining: Int = 0
        var minTraining: Int = 255
        
        var barDatas: [HeartBarData] = []
        
        details.enumerated().forEach { i, detail in
            
            //            print(i)
            print(detail.maxHeartRate)
            print(detail.minHeartRate)
            //            print("----")
            
            if max < detail.maxHeartRate {
                max = detail.maxHeartRate
            }
            if min > detail.minHeartRate && detail.minHeartRate > 0  {
                min = detail.minHeartRate
            }
            
            if detail.avgHeartRate > 0 && detail.type != .training {
                avgAll += detail.avgHeartRate
                count += 1
                
                rangeAvg += detail.avgHeartRate
                rangeCount += 1
            }
            
            switch detail.type {
                
            case .dayTime:
                
                if maxDayTime < detail.maxHeartRate {
                    maxDayTime = detail.maxHeartRate
                }
                if minDayTime > detail.minHeartRate {
                    minDayTime = detail.minHeartRate
                }
                
                break
            case .sleeping:
                
                if maxSleep < detail.maxHeartRate {
                    maxSleep = detail.maxHeartRate
                }
                if minSleep > detail.minHeartRate {
                    minSleep = detail.minHeartRate
                }
                
                
                break
            case .training:
                
                if maxTraining < detail.maxHeartRate {
                    maxTraining = detail.maxHeartRate
                }
                if minTraining > detail.minHeartRate {
                    minTraining = detail.minHeartRate
                }
                
                break
                
            }
            
            
            var avg = 0
            if rangeCount > 0 {
                avg = rangeAvg/rangeCount
            }
            
            if minSleep > maxSleep || minSleep == 0 {
                minSleep = maxSleep
            }
            
            if minTraining > maxTraining || minTraining == 0 {
                minTraining = maxTraining
            }
            if minDayTime > maxDayTime || minDayTime == 0 {
                minDayTime = maxDayTime
            }
            
            let sleeping = HeartBarDataValue(high: Double(maxSleep), low: Double(minSleep))
            let workouts = HeartBarDataValue(high: Double(maxTraining), low: Double(minTraining))
            let dayTime = HeartBarDataValue(high: Double(maxDayTime), low: Double(minDayTime))
            
            let endTime = date.dateAtStartOf(.day) + i.minutes
            let startTime = endTime - 30.minutes
            
            let barData = HeartBarData(dayTime: dayTime, sleeping: sleeping, workouts: workouts, startTime: startTime.timeIntervalSince1970, endTime: endTime.timeIntervalSince1970, avg: avg)
            barDatas.append(barData)
            
            
            maxDayTime = 0
            minDayTime = 255
            
            maxSleep = 0
            minSleep = 255
            
            maxTraining = 0
            minTraining = 255
            
            rangeAvg = 0
            rangeCount = 0
            
            
        }
        
        if min > max {
            min = max
        }
        
        var avg = 0
        if count > 0 {
            avg = avgAll/count
        }
        
        return (barDatas, max, min, avg)
        
    }

}
